
#include "hal_timer.h"

#include<Windows.h>
#include<stdio.h>
//����һ��ʾ ��Ҫ�ȴ���ʱ�� ΢��Ϊ��λ
int UsSleep(int us)
{
    //�������������
    LARGE_INTEGER fre;
    //��ȡӲ��֧�ֵĸ߾��ȼ�������Ƶ��
    if (QueryPerformanceFrequency(&fre))
    {
        LARGE_INTEGER run,priv,curr;
        run.QuadPart = fre.QuadPart * us / 1000000;//ת��Ϊ΢�
        //��ȡ�߾��ȼ�������ֵ
        QueryPerformanceCounter(&priv);
        do
        {
            QueryPerformanceCounter(&curr);
        } while (curr.QuadPart - priv.QuadPart < run.QuadPart);
        curr.QuadPart -= priv.QuadPart;
        int nres = (curr.QuadPart * 1000000 / fre.QuadPart);//ʵ��ʹ��΢��ʱ��
        return nres;
    }
    return -1;//
}


static uint16_t timer0_p = 0;
void TIM0_IRQHandler(void);
DWORD WINAPI TIMER0_INT(LPVOID p)
{
	while(1){
		if(timer0_p != 0){
			while(1){
//				printf("TIMER0_INT\r\n");
				TIM0_IRQHandler();
				Sleep(timer0_p);
			}
		}
		Sleep(100);
	}

    return 0;
}
static uint16_t timer1_p = 0;
void TIM1_IRQHandler(void);
DWORD WINAPI TIMER1_INT(LPVOID p)
{
	int us;
	while(1){
//		printf("TIMER1_INT\r\n");
		TIM1_IRQHandler();
		us = UsSleep(500);
		if(us == -1){
			printf("us err\r\n");
		}
		else{
//			printf("us: %d\r\n",us);
		}

	}
    return 0;
}

void TIM_TimeBaseInit(TIM_TypeDef* TIMx, TIM_TimeBaseInitTypeDef* TIM_TimeBaseInitStruct)
{
	if((uint16_t)TIMx == TIM0){
		timer0_p = TIM_TimeBaseInitStruct->TIM_Period;
		CreateThread(NULL, 0, TIMER0_INT, 0, 0, NULL);
	}
	else if((uint16_t)TIMx == TIM1){
		timer1_p = TIM_TimeBaseInitStruct->TIM_Period;
		CreateThread(NULL, 0, TIMER1_INT, 0, 0, NULL);
	}
}

void TIM_Cmd(TIM_TypeDef* TIMx, FunctionalState NewState)
{

}
void TIM_ITConfig(TIM_TypeDef* TIMx, uint16_t TIM_IT, FunctionalState NewState)
{

}
